from django.contrib.auth import get_user_model

from backend.cews.models import RepairOrder, DepotList, CCEmailModel, RepairOrderRepairDetails
from backend.cews.services import emailService as EmailService
from django.utils import timezone

from datetime import timedelta, datetime
from django.core.mail import EmailMessage, send_mail, EmailMultiAlternatives
from dateutil.relativedelta import relativedelta
from django.template.loader import render_to_string

from config import celery_app
from celery.schedules import crontab

from logger.createlogger import create_logger

User = get_user_model()

logger = create_logger('CEWSCeleryTask')


@celery_app.task()
def send_email_when_repair_order_non_active():

    ## get non active order, definition: (today - last action date) >  3 days and order not complete
    today = timezone.now().date()

    users = User.objects.all()
    three_days_ago = today - timedelta(days=3)
    for user in users:
        if user.email and user.enable_email:
            r_objs = RepairOrder.objects.filter(complete_by=None,last_action_date__lt=three_days_ago,created_by=user)
            if r_objs.exists():
                logger.info("Send email to {}: {}".format(user, user.email))
                email_template = render_to_string(
                        'emails/remind_email.html',
                        {'user':user, 'r_objs':r_objs}
                    )
                subject = "Reminder - CEWS Non-active Items In Maintenance Order"
                EmailService.emailAction(subject, user.email, '', email_template)
    

##copy from io system

# @celery_app.task()
def email2Depot():
    
    logger.info("******************************************Send email to depot")

    depots=DepotList.objects.all()
    
    # outstanding more than 1 week
    
    today=datetime.today()
    delta = relativedelta(days=6)
    over_ove_week = today - delta
    
    for depot in depots:
        email=depot.email

        if email:
            logger.info("Send email to {}: {}".format(depot, email))
            # wo_objs = WorkOrderList.objects.filter(deliverto=depot)
            # nff_objs=RepairOrderRepairDetails.objects.filter(his_obj__wo__deliverto=depot, his_obj__wo__test_status__isnull=True, his_obj__checkouttime__lte=over_ove_week).exclude(his_obj__wo__repeatcase=False)
            # correct
            nff_objs=RepairOrderRepairDetails.objects.filter(delivery_to=depot,maintenance_type='NFF', repair_order__check_out__lte=over_ove_week).exclude(repeat_within_six_months=RepairOrderRepairDetails.ResultType.NO)
            # nff_objs=RepairOrderRepairDetails.objects.filter(delivery_to=depot,maintenance_type='NFF').exclude(repeat_within_six_months=RepairOrderRepairDetails.ResultType.NO)
            logger.info("nff_objs {}".format(nff_objs))
            
            if nff_objs.exists():
                email_template = render_to_string(
                        'emails/depot_email.html',
                        {'depot':depot, 'nff_objs':nff_objs}
                    )

                subject = "Reminder - CEWS NFF Items Depot Monitoring Result"
                cc_obj=CCEmailModel.objects.first()
                if cc_obj:
                    cc_list=cc_obj.emails
                    cc_list=list(filter(None, cc_obj.emails.split(",")))
                else:
                    cc_list=[]

                cc_str = ','.join(cc_list)
      
                EmailService.emailAction(subject, email, cc_str, email_template)


schedule = {
    # 'email-to-deport': { ### to be confirmed
    #     'task': 'backend.cews.tasks.email2Depot',
    #     'schedule': crontab(hour=9, minute=0),
    # },
   'email-to-order-owner': { 
        'task': 'backend.cews.tasks.send_email_when_repair_order_non_active',
        'schedule': crontab(hour=9, minute=0),
    },
    }

celery_app.conf.beat_schedule = schedule